package com.cskaoyan.typehandler;


import com.cskaoyan.utils.JacksonUtil;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@MappedTypes(List.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class ListTypeHandler implements TypeHandler<List> {

    @Override
    public void setParameter(PreparedStatement ps, int i, List parameter, JdbcType jdbcType) throws SQLException {
        String str = JacksonUtil.write(parameter);
        ps.setString(i,str);
    }

    @Override
    public List getResult(ResultSet rs, String columnName) throws SQLException {
        String str = rs.getString(columnName);
        List list = JacksonUtil.read(str, List.class);
        return list;
    }

    @Override
    public List getResult(ResultSet rs, int columnIndex) throws SQLException {
        String str = rs.getString(columnIndex);
        List list = JacksonUtil.read(str, List.class);
        return list;
    }

    @Override
    public List getResult(CallableStatement cs, int columnIndex) throws SQLException {
        return JacksonUtil.read(cs.getString(columnIndex), List.class);
    }
}
